import { ref, onMounted, reactive } from "vue";
import { message } from "@/utils/message";
import { useRoute, useRouter } from "vue-router";

import { getCategoryList } from "@/api/category";
import { getTagDictionary } from "@/api/tag";
import {
  addArticle,
  editArticle,
  getArticleById,
  titleExist
} from "@/api/article";
import { mdImgUpload } from "@/api/site";
import { tagV, coverV } from "./validator";

export function useArticle() {
  const dialogVisible = ref(false);
  const articleFormRef = ref();
  const dialogArticleFormRef = ref();
  const route = useRoute();
  const router = useRouter();
  const canPublish = ref(true);

  const articleForm = reactive({
    id: "",
    title: "",
    cateGoryId: 0,
    tagIds: [],
    imageUrlList: [],
    content: "",
    cover: "",
    isTop: 2, // 置顶 1 置顶 2 取消置顶
    status: 1, // 状态 1 公开 2 私密 3 回收站（相当于草稿）
    type: 1, // 类型 1 原创 2 翻译 3 转载
    originUrl: "", // 原文链接 翻译或转载才需要填

    description: "" // 文章描述
  });

  const tagOptionList = ref([]);
  const categoryOptionList = ref([]);

  const coverPreviewVisible = ref(false);
  const coverUrl = ref(null);

  // 校验规则category_idcategory_id
  const articleFormRules = reactive({
    title: {
      required: true,
      trigger: "blur",
      message: "请输入文章标题"
    },
    content: {
      required: true,
      message: "请输入文章内容",
      trigger: "blur"
    }
  });
  // 校验规则
  const dialogArticleFormRules = reactive({
    categoryId: {
      required: true,
      message: "请选择文章分类",
      trigger: ["change"]
    },
    description: {
      required: true,
      message: "请输入文章描述",
      trigger: ["blur"]
    },
    tagIds: {
      required: true,
      message: "请选择文章标签",
      validator: tagV,
      trigger: ["change"]
    },
    imageUrlList: {
      required: true,
      message: "请上传文章封面",
      validator: coverV,
      trigger: ["change"]
    },
    originUrl: {
      required: true,
      message: "请输入原文链接",
      trigger: ["blur"]
    }
  });

  function closeDialog() {
    resetForm(dialogArticleFormRef.value);
    dialogVisible.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
  };

  // 发布文章 打开弹窗
  async function publish(formEl) {
    if (!formEl) return;
    if (!canPublish.value) {
      message("文章标题重复，换个标题试试", { type: "warning" });
      return;
    }
    await formEl.validate(valid => {
      if (valid) {
        dialogVisible.value = true;
      } else {
        message("请按照提示填写信息", { type: "warning" });
      }
    });
  }

  async function articleTitleVAlidate() {
    const { id, title } = articleForm;
    const res = await titleExist({ id, title });
    if (res.result) {
      canPublish.value = false;
      message("文章标题已存在，换一个试试", { type: "warning" });
    } else {
      canPublish.value = true;
    }
  }

  // 上传md文章图片
  async function uploadImage(files, callback) {
    const res = await Promise.all(
      files.map(file => {
        return new Promise((resolve, reject) => {
          mdImgUpload(file).then(imgData => {
            if (imgData.code == 0) {
              const { url } = imgData.result;
              resolve(url);
            } else {
              reject(imgData.message || "上传失败");
            }
          });
        });
      })
    );

    callback(res);
  }

  // 发布
  async function submitForm(formEl, type) {
    await formEl.validate(async valid => {
      if (valid) {
        // 图片上传

        if (type == 1) {
          // 1 是保存草稿 2 是直接发布
          articleForm.status = 3;
        }
        // 整合数据
        if (articleForm.imageUrlList.length) {
          articleForm.cover = articleForm.imageUrlList[0];
        } else {
          articleForm.cover = "";
        }
        let res;
        if (!articleForm.id) {
          // 新增
          res = await addArticle(articleForm);
        } else {
          // 编辑
          res = await editArticle(articleForm);
        }
        if (res.code == 0) {
          message(res.message, { type: "success" });
          resetForm(formEl.value);
          resetForm(articleFormRef.value);
          dialogVisible.value = false;
          setTimeout(() => {
            router.push("/article/articleList");
          }, 300);
        }
      } else {
        message("请按照提示填写信息", { type: "warning" });
      }
    });
  }

  // 获取标签列表
  async function getTagD() {
    const res = await getTagDictionary();
    if (res.code == 0) {
      tagOptionList.value = res.result.rows;
    }
  }
  // 获取分类列表
  async function getCategoryD() {
    const res = await getCategoryList();
    if (res.code == 0) {
      categoryOptionList.value = res.result.rows;
    }
  }
  // 根据id获取文章详情
  async function getArticleDetailsById(article_id) {
    const res = await getArticleById(article_id);
    if (res.code == 0) {
      const { cover } = res.result;
      Object.assign(articleForm, res.result);

      articleForm.cover = cover[0];
    }
  }

  onMounted(async () => {
    getCategoryD();
    await getTagD();

    if (!route.query.articleId) return;
    // 根据id获取文章信息
    getArticleDetailsById(route.query.articleId);
  });

  return {
    coverUrl,
    articleForm,
    dialogVisible,
    tagOptionList,
    articleFormRef,
    articleFormRules,
    categoryOptionList,
    coverPreviewVisible,
    dialogArticleFormRef,
    dialogArticleFormRules,
    closeDialog,
    uploadImage,
    publish,
    submitForm,
    articleTitleVAlidate
  };
}
